What is clone-regexp?
The clone-regexp npm package is designed to clone regular expressions with the option to modify their properties such as flags, source, and lastIndex. This can be useful when you need to reuse a regular expression with slight variations or reset its state without affecting the original regex.
What are clone-regexp's main functionalities?
Cloning a regular expression
This feature allows you to create a copy of an existing regular expression. The cloned regex will have the same source and flags as the original.
const cloneRegexp = require('clone-regexp');
const regex = /[a-z]/gi;
const clonedRegex = cloneRegexp(regex);
console.log(clonedRegex); // Output: /[a-z]/gi
Modifying flags
This feature allows you to clone a regular expression and modify its flags. In this example, the 'i' flag is removed, and the 'm' flag is added.
const cloneRegexp = require('clone-regexp');
const regex = /[a-z]/gi;
const clonedRegex = cloneRegexp(regex, {flags: 'gm'});
console.log(clonedRegex); // Output: /[a-z]/gm
Changing the lastIndex
This feature allows you to clone a regular expression and set the lastIndex property. This is useful when you want to reset the state of the regex for a new search.
const cloneRegexp = require('clone-regexp');
const regex = /[a-z]/gi;
regex.lastIndex = 10;
const clonedRegex = cloneRegexp(regex, {lastIndex: 0});
console.log(clonedRegex.lastIndex); // Output: 0
Other packages similar to clone-regexp
regexp-clone
The regexp-clone package provides similar functionality to clone-regexp by allowing users to clone regular expressions. It preserves the source, flags, and lastIndex of the original regex. The main difference is in the implementation and possibly in the specific features or options provided by each package.
clone
The clone package is a more general utility for cloning objects, arrays, dates, and regular expressions in JavaScript. While it can clone regular expressions like clone-regexp, it is not specialized for regex cloning and does not provide options to modify the cloned regex's properties.
clone-regexp 
Clone and modify a RegExp instance
Install
$ npm install clone-regexp
Usage
const cloneRegexp = require('clone-regexp');
const regex = /[a-z]/gi;
cloneRegexp(regex);
cloneRegexp(regex) === regex;
cloneRegexp(regex, {global: false});
cloneRegexp(regex, {multiline: true});
cloneRegexp(regex, {source: 'unicorn'});
API
cloneRegexp(regexp, [options])
regex
Type: RegExp
Regex to clone.
options
Type: Object
Properties: source
global
ignoreCase
multiline
dotAll
sticky
unicode
lastIndex
Optionally modify the cloned RegExp
instance.
License
MIT © Sindre Sorhus